package com.sudo.boot.service.wx.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sudo.boot.base.exception.BizException;
import com.sudo.boot.base.exception.BootException;
import com.sudo.boot.mapper.sys.entity.SysUser;
import com.sudo.boot.mapper.sys.mapper.SysUserMapper;
import com.sudo.boot.mapper.wx.entity.WxUser;
import com.sudo.boot.mapper.wx.mapper.WxUserMapper;
import com.sudo.boot.service.wx.WxUserService;
import com.sudo.boot.service.wx.converter.WxUserConverter;
import com.sudo.boot.weixin.pojo.WeChatUser;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.sudo.boot.mapper.wx.entity.table.WxUserTableDef.WX_USER;

@Slf4j
@Service
@RequiredArgsConstructor
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements WxUserService {
    @Resource
    private WxUserMapper wxUserMapper;
    @Resource
    private WxUserConverter wxUserConverter;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public void bindWxUser(String sysUserId, WeChatUser weChatUser) {
        long longUserId = Long.parseLong(sysUserId);
        // 1.判断当前用户是否已经绑定微信
        SysUser sysUser = sysUserMapper.selectOneById(longUserId);
        if (sysUser == null) {
            throw new BootException("用户不存在，请先注册");
        }
        // 2.判断用户是否已经绑定微信
        WxUser wxUser = wxUserMapper.selectOneByCondition(WX_USER.SYS_USER_ID.eq(longUserId));
        if (wxUser != null) {
            throw new BootException("已绑定，请先解绑");
        }
        wxUser = wxUserConverter.toWxUser(weChatUser);
        wxUser.setSysUserId(longUserId);

        // 新增微信用户信息
        wxUserMapper.insert(wxUser);
    }

    @Override
    public void unbindWx(Long sysUserId) {
        WxUser wxUser = wxUserMapper.selectOneByCondition(WX_USER.SYS_USER_ID.eq(sysUserId));
        if (Objects.isNull(wxUser)) {
            throw new BizException("暂未绑定微信");
        }
        // 删除微信用户信息
        wxUserMapper.deleteById(wxUser.getId());
        log.info("微信解绑：sysUserId={}", sysUserId);
    }

    @Override
    public boolean bindWxStatus(Long sysUserId) {
        WxUser wxUser = wxUserMapper.selectOneByCondition(WX_USER.SYS_USER_ID.eq(sysUserId));
        return Objects.nonNull(wxUser);
    }

    @Override
    public WxUser getWxUserByOpenId(String openId) {
        return wxUserMapper.selectOneByCondition(WX_USER.OPENID.eq(openId));
    }
}
